
package com.probiz.estoresf.customer.web.action;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.AttributeUtil;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.attribute.AttributeValue;
import com.probiz.estore.common.model.attribute.CustomerAttrValue;
import com.probiz.estore.common.model.customer.Customer;
import com.probiz.estore.common.model.customer.ValidationSession;
import com.probiz.estore.core.controller.GenericCustomerFrontController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.customer.model.CustomerFullyModel;
import com.probiz.estore.customer.service.CustomerManager;
import com.probiz.estore.customer.service.ValidationSessionManager;
import com.probiz.estore.system.service.MsgSendManager;
import com.probiz.estore.system.util.MsgTemplateConstants;
import com.probiz.estore.util.ipwry.IPSeeker;
import com.probiz.estore.webapp.util.RequestUtil;


public class CustomerRegisterFrontController extends GenericCustomerFrontController<Customer> {
	 private ValidationSessionManager validationSessionManager;
	 private CustomerManager customerManager ;
	 private MsgSendManager msgSendManager;


     public void setMsgSendManager(MsgSendManager msgSendManager) {
		this.msgSendManager = msgSendManager;
	}


	public void setCustomerManager(CustomerManager customerManager) {
        this.customerManager = customerManager;
     }
     
 		
	public void setValidationSessionManager(
			ValidationSessionManager validationSessionManager) {
		this.validationSessionManager = validationSessionManager;
	}


	@Override
	protected String getEntityName(Customer entity) {
		return null;
	}

	@Override
	protected Map<Integer, Map<String, Object>> getMultiSaveModel(
			HttpServletRequest request) {
		return null;
	}

	@Override
	protected void initController() throws Exception {
		
	}

	@Override
	public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("customer/register");
		Customer customer = this.formBackingObject(request);
		mv.addObject("customer", customer);
		return mv;
	}
	
	@Override
	protected void preSave(HttpServletRequest request, Customer customer, BindException errors) {
    	boolean isDuplicate = customerManager.getIsUserExist(customer.getUsername());
    	if (isDuplicate) {
			//检查账户是否重复
			errors.rejectValue("username", "appUser.username.isExist", "the username has exist !");
		} else if (customerManager.getIsEmailExist(customer.getEmail())) {
			//检查邮件地址是否已存在
			errors.rejectValue("email", "appUser.email.isExist", "the email has exist!");
		}
	}
	/**
	 * 检查账户是否重复
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView checkIsUserExist(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String username = RequestUtil.getParameterNullSafe(request, "username");
		Map<String,Object> data = new HashMap<String ,Object>();
		data.put("username", username);
		boolean isDuplicate = customerManager.getIsUserExist(username);
    	if (isDuplicate) {
    		data.put("isUserNamePass", 0);
    	}else{
    		data.put("isUserNamePass", 1);
    	}
    	return this.getModelAndAjaxJsonView(data);
	}
	/**
	 * 检查邮件地址是否已存在
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView checkIsEmailExist(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String email = RequestUtil.getParameterNullSafe(request, "email");
		Map<String,Object> data = new HashMap<String ,Object>();
		data.put("email", email);
		boolean isDuplicate = customerManager.getIsEmailExist(email);
		if (isDuplicate) {
			data.put("isEmailPass", 0);
		}else{
			data.put("isEmailPass", 1);
		}
		return this.getModelAndAjaxJsonView(data);
	}
	
	/**
	 * 检查账户和邮件地址是否已存在
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView checkRegisterForm(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String username = RequestUtil.getParameterNullSafe(request, "username");
		Map<String,Object> data = new HashMap<String ,Object>();
		data.put("username", username);
    	if (customerManager.getIsUserExist(username)) {
    		data.put("isUserNamePass", 0);
    	}else{
    		data.put("isUserNamePass", 1);
    	}
    	
		String email = RequestUtil.getParameterNullSafe(request, "email");
		data.put("email", email);
		if (customerManager.getIsEmailExist(email)) {
			data.put("isEmailPass", 0);
		}else{
			data.put("isEmailPass", 1);
		}
		return this.getModelAndAjaxJsonView(data);
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.core.controller.GenericCustomerFrontController#save(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 * 
	 * 注册新用户
	 */
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> data = new HashMap<String ,Object>();
		//--------start:绑定注册项，出错时候可以还原--------
		List<AttributeValue> attributeValueList = AttributeUtil.getInstance().getAttributeFromRequest(request);
		Customer customer = this.formBackingObject(request);
		String password = null;
		Set<CustomerAttrValue> customerAttributeValueSet = new HashSet<CustomerAttrValue>();
		for(AttributeValue attributeValue :attributeValueList){
			customerAttributeValueSet.add((CustomerAttrValue)attributeValue);
		}
		customer.setCustomerAttrValues(customerAttributeValueSet);
		//--------end:绑定注册项，出错时候可以还原--------
		
		customer.setRemoteIp(request.getRemoteAddr());
		customer.setAddress(IPSeeker.getInstance().getAddress(customer.getRemoteIp()));
		BindException errors = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, customer);
			errors = new BindException(binder.getBindingResult());
			password = customer.getPassword();
			preSave(request, customer, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				
				CustomerFullyModel model = new CustomerFullyModel();
				model.setCustomer(customer);
				model.setAttributeValues(attributeValueList);
				Map<String,Object> returnMsgs = customerManager.doRegisterCustomer(model);//前台激活
				data.putAll(returnMsgs);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}
		
		ModelAndView mv;
		if (errors.hasErrors()) {
			mv = new ModelAndView("customer/register",errors.getModel());
			mv.addObject("attributeValueList", attributeValueList);  //注入注册项
		} else {
			Short activeMode = (Short)data.get("activeMode");
			if(Constants.CUSTOMER_ACTIVE_NOW.equals(activeMode)){
				//如果是立刻激活。
				if(ConfigUtil.getInstance().isOpenCasService()){
					//如果是CAS方式需要重新填写一次
					mv = new ModelAndView("redirect:/login.html?"+Constants.SAVED_URL_KEY+"="+RequestUtil.getAppURL(request)+"/customer/registerSuccess.html");
				}else{
					mv = new ModelAndView("forward:/j_security_check?j_username="+customer.getEmail()+"&j_password="+password+"&"+Constants.SAVED_URL_KEY+"="+RequestUtil.getAppURL(request)+"/customer/registerSuccess.html");
				}
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("customer", customer);
				msgSendManager.sendMsg(MsgTemplateConstants.MESSAGE_FRONT_USER_ACTIVATION, model, 
						null, 
						null != customer.getCustomerId() ? new String[]{customer.getCustomerId().toString()} : null, 
						null != customer.getMobilephone() ? new String[]{customer.getMobilephone()} : null);//激活用户，并发送系统消息
			}else{
				mv = new ModelAndView("customer/registerSuccess");
				mv.addAllObjects(data);
			}
			
		}
		return mv;
	}
	
	/**
	 * 再次发送注册激活邮件
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView sendActiveEmailAgain(HttpServletRequest request, HttpServletResponse response) {
		customerManager.sendValidationMail(request.getParameter("email"));
		return this.getModelAndAjaxJsonView(null);
	}
	
	/**
	 * 通过链接激活用户
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView activeUser(HttpServletRequest request, HttpServletResponse response) {
		String uid = request.getParameter("uid");
		if (uid != null && !"".equals(uid)) {
			ValidationSession vs = validationSessionManager.getByUrlType(uid, ValidationSession.TYPE_CUSTOMER_ACTIVE);
			if (vs != null) {// validate,the update customer validate
				customerManager.saveAppUserStatusByEmail(vs.getEmail(), Constants.STATUS_ACTIVE);
				request.setAttribute("isRight", true);
			} else {
				// no validate
				request.setAttribute("isRight", false);
			}
		} else {
			request.setAttribute("isRight", false);
		}
		return new ModelAndView("/customer/activateUser");
	}
	
}
